import {useEffect, useState} from 'react';
import {useUpdate} from './useUpdate';

export type RecordItem = {
  tagIds: number[],
  note: string,
  category: '+' | '-',
  amount: number,
  createAt: string // ISO8601
}
type newRecordItem = Omit<RecordItem, 'createAt'>
const useRecords = () => {
  const [records, setRecords] = useState<RecordItem[]>([]);
  useEffect(() => {
    setRecords(JSON.parse(localStorage.getItem('records') || '[]'));
  }, []);
  const addRecord = (newRecordItem: newRecordItem) => {
    if (newRecordItem.amount <= 0) {
      return false
    }
    if(newRecordItem.tagIds.length===0){
      alert('请选择标签')
      return false
    }
    const record: RecordItem = {...newRecordItem, createAt: new Date().toISOString()};
    setRecords([...records, record]);
    return true
  };
  useUpdate(() => {
    window.localStorage.setItem('records', JSON.stringify(records));
  }, records);
  return {records, addRecord};
};
export {useRecords};